package com.itheima.tanhuauser.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.dto.ThFollowDto;
import com.itheima.pojo.ThFollow;
import com.itheima.pojo.User;
import com.itheima.tanhuauser.mapper.UserMapper;
import com.itheima.tanhuauser.service.UserService;
import com.itheima.tanhuauser.thread.TokenThread;
import com.itheima.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public boolean sendMsg(String phone) {
        Random random = new Random();
        Integer number = random.nextInt(99999)+100000;
        String code = number.toString();
        log.info("{}",number);
        redisTemplate.opsForValue().set("user_code:"+phone,code,2L, TimeUnit.DAYS);
        return true;
    }

    @Override
    public UserVo login(UserVo userVo) {
        if (userVo.getPhone()==null&&userVo.getCode()==null){
            throw new RuntimeException();
        }
        String codePhone =(String) redisTemplate.opsForValue().get("user_code:" + userVo.getPhone());
        if (codePhone==null || !codePhone.equals(userVo.getCode())){
            throw new RuntimeException();
        }
        User user=userMapper.selectByPhone(userVo.getPhone());
        if (user==null){
            User newUser = new User();

            BeanUtils.copyProperties(userVo,newUser);
            String id = IdUtil.getSnowflakeNextIdStr();
            newUser.setId(id);
            int res=userMapper.addUser(newUser);
            if (res == 0) {
                throw new RuntimeException();
            }
            user = new User();
            BeanUtils.copyProperties(newUser,user);
        }
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(user,vo);
        String key = "linzinan";
        Map<String,Object> map = new HashMap<>();
        map.put("name",user.getName());
        String token = JWTUtil.createToken(map, key.getBytes());
        redisTemplate.opsForValue().set("user_token:"+token, JSON.toJSONString(user),2L,TimeUnit.DAYS);
        vo.setToken(token);
        log.info("loginVo:{}",vo);
        return vo;
    }

    @Override
    public boolean updateMsg(UserVo userVo) {
        int res=userMapper.updateMsg(userVo);
        if (res==0){
            throw new RuntimeException("完善个人信息失败");
        }
        return true;
    }

    @Override
    public List<User> findLike(Integer type,String id,String name,Integer page,Integer pageSize) {

        if (type==1){
            List<User> list1=userMapper.someoneLike(id);
            return list1;
        }
        else if (type==2){
            List<User> list2=userMapper.likeSomeOne(id);
            return list2;
        }
        return userMapper.likeEachOther(id);
    }

    @Override
    public boolean addLike(ThFollowDto thFollowDto) {
        ThFollow thFollow = new ThFollow();
        thFollow.setId(IdUtil.getSnowflakeNextIdStr());
        String userId = TokenThread.get();
        thFollow.setUserId(userId);
        thFollow.setFollowId(thFollowDto.getUserId());
        thFollow.setCreateTime(LocalDateTime.now());
        int res=userMapper.addLike(thFollow);
        if (res==0){
            throw new RuntimeException("添加喜欢失败");
        }
        return true;
    }

    @Override
    public boolean deleteLike(String followId) {
        int res=userMapper.deleteLike(followId);
        if (res==0){
            throw new RuntimeException("取消失败");
        }
        return true;
    }
}
